package com.geiliwang.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.geiliwang.web.config.RedisClient;
import com.geiliwang.web.config.SmsTempateCodeEnum;
import com.geiliwang.web.entity.*;
import com.geiliwang.web.enums.ArticleTypeEnum;
import com.geiliwang.web.enums.InvestStyleEnum;
import com.geiliwang.web.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private PlatformService platformService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private PlatformgroupService platformgroupService;
    @Autowired
    private FriendLinkService friendLinkService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private PlatformareaService platformareaService;
    @Autowired
    private PlatformschemeService platformschemeService;
    @Autowired
    private SmsService smsService;
    @Value("${manage.username}")
    private String manageUsername;
    @Value("${manage.passwd}")
    private String managePasswd;
    @Value("${start.operation}")
    private String startOperation;

    @RequestMapping("/")
    public String frontIndex(Model model, HttpServletRequest request){
        //平台总数量
        int platformCount = platformService.findPlatformCount();
        //banner轮播
        List<Banner> bannerList = bannerService.findUsedBanners();
        //置顶平台
        //List<Platform> tops = platformService.findTopPlatform();
        //平台分组
        List<PlatformGroupVO> platformGroupVOList =platformgroupService.findAllGroup();
        //友情链接
        List<FriendLink> friendLinks = friendLinkService.findUsedLink();
        //用户数量
        int memberCount = memberService.findMemberCount();
        //正常运营天数
        if(StringUtils.isNoneBlank(startOperation)){
            model.addAttribute("operationDay",calcDays(startOperation));
        }else{
            model.addAttribute("operationDay",99);
        }

        model.addAttribute("memberCount",memberCount);
        model.addAttribute("friendLinks",friendLinks);
        model.addAttribute("platformGroupVOList",platformGroupVOList);
        //model.addAttribute("tops",tops);
        model.addAttribute("bannerList",bannerList);
        request.getSession().setAttribute("platformCount",platformCount);
        model.addAttribute("active","home");
        return "/front/index";
    }

    private long calcDays(String startDate){
        try {
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.now();
            return ChronoUnit.DAYS.between(start, end);
        } catch (Exception e) {
            System.out.println("计算运营天数出错");
            e.printStackTrace();
            return 99;
        }
    }

    /**
     * 注册
     * @return
     */
    @RequestMapping("/toSignUp")
    public String toSignUp(@RequestParam(value = "inviteId",required = false)Long inviteId, Model model){
        model.addAttribute("inviteId",inviteId);
        return "/front/user-signup";
    }

    /**
     * 前台登陆
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "/front/user-login";
    }

    /**
     * 找回密码
     * @return
     */
    @RequestMapping("/toFindPass")
    public String toFindPass(){
        return "/front/user-find-pass";
    }
    @ResponseBody
    @RequestMapping("/sendSmsCode")
    public HttpEntity<String> sendSmsCode(String phone){
        if(StringUtils.isNoneBlank(phone)){
            //查询此手机号是否为注册用户
            MemberQuery query = new MemberQuery();
            query.setEmail(phone);
            PageInfo<Member> memberPageInfo = memberService.queryBy(query);
            if(!CollectionUtils.isEmpty(memberPageInfo.getList())) {
                try {
                    String messageId = smsService.sendSmsVcode(phone, "", SmsTempateCodeEnum.SMS_TEST.getCode(), new HashMap<>());
                    return ResponseEntity.status(HttpStatus.OK).body(messageId);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("短信发送失败");
                }
            }
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("手机号有误");
    }

    @RequestMapping("/findPass")
    public String findPass(String phone,String messageId,String vcode,String password,Model model){
        try {
            boolean result = smsService.checkSmsVcode(messageId,vcode,phone);
            if(result && StringUtils.isNoneBlank(password)){
                MemberQuery query = new MemberQuery();
                query.setEmail(phone);
                PageInfo<Member> memberPageInfo = memberService.queryBy(query);
                if(!CollectionUtils.isEmpty(memberPageInfo.getList())){
                    Member member = memberPageInfo.getList().get(0);
                    member.setPasswd(new String(DigestUtils.md5(password.getBytes())));
                    memberService.updateById(member);
                    return "redirect:/toLogin";
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        model.addAttribute("msg","修改失败");
        return "/front/user-find-pass";
    }

    @ResponseBody
    @RequestMapping("/existEmail")
    public HttpEntity<Boolean> existEmail(String email){
        EntityWrapper<Member> ew = new EntityWrapper<>();
        ew.eq("email",email);
        Member member = memberService.selectOne(ew);
        if(null != member){
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.ok(false);
    }

    @RequestMapping("/register")
    public String register(@Valid Member member,HttpServletRequest request){
        boolean flag = memberService.register(member);
        if(flag){
            request.getSession().setAttribute("member",member);
            return "redirect:/";
        }
        return "/404";
    }

    /**
     * 登陆
     * @return
     */
    @RequestMapping("/login")
    public String login(String email, String passwd, Model model, HttpServletRequest request){
        EntityWrapper<Member> ew = new EntityWrapper<>();
        ew.eq("email",email);
        ew.eq("passwd",new String(DigestUtils.md5(passwd)));
        Member member = memberService.selectOne(ew);
        if(null != member){
            request.getSession().setAttribute("member",member);

            return "redirect:/";
        }
        model.addAttribute("msg","用户名或密码错误");
        return "/front/user-login";
    }

    /**
     * 后台登陆
     * @return
     */
    @RequestMapping("/toManageLogin")
    public String toManageLogin(){
        return "/pages/login";
    }

    @RequestMapping("/manageLogin")
    public String manageLogin(HttpServletRequest request){
        String username = request.getParameter("username");
        String passwd = request.getParameter("passwd");
        if(StringUtils.equals(manageUsername,username) && StringUtils.equals(managePasswd,passwd)){
            request.getSession().setAttribute("manage","manage");
            return "redirect:/manage";
        }
        request.setAttribute("msg","用户名或密码错误");
        return "/pages/login";
    }

    @RequestMapping("/article/articleList")
    public String frontList(ArticleQuery query,Model model){
        PageInfo<Article> articlePageInfo = articleService.queryBy(query);
        model.addAttribute("articlePageInfo",articlePageInfo);
        model.addAttribute("query",query);
        model.addAttribute("typeEnums", ArticleTypeEnum.values());
        model.addAttribute("active","articleList");
        return "/front/news_list";
    }

    @RequestMapping("/article/detail")
    public String frontDetail(@RequestParam("id")Long id,Model model){
        Article article = articleService.selectById(id);
        model.addAttribute("article",article);
        return "/front/news-detail";
    }

    @RequestMapping("/platform/list")
    public String platformList(Platform platform, Model model){

        EntityWrapper<Platform> ew = new EntityWrapper<>();
        ew.where("delFlag='0'");
        if(null != platform.getAreaId()) {
            ew.eq("areaId", platform.getAreaId());
        }
        if(StringUtils.isNoneBlank(platform.getInvestCount())) {
            ew.eq("investCount", platform.getInvestCount());
        }
        List<Platform> platformList =  platformService.selectList(ew);
        List<Platformarea> platformareaList = platformareaService.selectAllNoDel();
        model.addAttribute("invests", InvestStyleEnum.values());
        model.addAttribute("platformList",platformList);
        model.addAttribute("platformareaList",platformareaList);
        model.addAttribute("active","platformList");
        model.addAttribute("platform",platform);
        return "/front/job-list";
    }

    @RequestMapping("/platform/detail")
    public String platformDetail(@RequestParam("id") Long id, Model model){
        Platform platform = platformService.selectById(id);
        if(null != platform){
            Map conditionMap = new HashMap();
            conditionMap.put("platformId",platform.getId());
            List<Platformscheme> platformschemeList = platformschemeService.selectByMap(conditionMap);
            PlatformVO platformVO = new PlatformVO();
            BeanUtils.copyProperties(platform,platformVO);
            platformVO.setSchemeList(platformschemeList);
            model.addAttribute("platformVO",platformVO);
            return "/front/job-detail";
        }
        return "404";
    }

    @RequestMapping("/about")
    public String about(Model model){
        model.addAttribute("active","about");
        return "/front/about";
    }

    @RequestMapping("/help")
    public String help(){
        return "/front/help";
    }

    @RequestMapping("/mz")
    public String mz(){
        return "/front/mianze";
    }
    @RequestMapping("/jb")
    public String jb(){
        return "/front/jubao";
    }
}
